<template>
  <div ref="boxRef" class="h-full w-full">
    <canvas ref="qrcodeRef" />
  </div>
</template>

<script lang='ts' setup>
import QRCode from 'qrcode'

interface Props {
  text?: string
}

const props = withDefaults(defineProps<Props>(), {
  text: '',
})

const qrcodeRef = ref<HTMLCanvasElement>()
const boxRef = ref<HTMLDivElement>()
async function generateQRCode() {
  try {
    await nextTick()
    if (!qrcodeRef.value || !boxRef.value) {
      return
    }
    const width = boxRef.value.clientWidth
    QRCode.toCanvas(qrcodeRef.value, props.text, {
      margin: 0,
      width,
    })
  }
  catch (err) {
    console.error(err)
  }
}

function save() {
  QRCode.toDataURL(props.text).then((url) => {
    const link = document.createElement('a')
    link.href = url
    link.download = 'qrcode.png'
    link.click()
    // window.location.href = 'www.baidu.com'
  })
}

onMounted(() => {
  watch(() => props.text, (val) => {
    if (val) {
      generateQRCode()
    }
  }, { immediate: true })
})

defineExpose({
  save,
})
</script>

<style lang='scss' scoped>
</style>
